package org.mao.forum.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.mao.base.BaseServiceImpl;
import org.mao.forum.dao.ForumSectionDao;
import org.mao.forum.entity.ForumSection;
import org.mao.forum.service.ForumSectionService;
import org.mao.forum.vo.ForumSectionVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;

@Service
public class ForumSectionServiceImpl extends BaseServiceImpl<ForumSection> implements ForumSectionService {

	private Logger logger = Logger.getLogger(ForumSectionServiceImpl.class);

	@Autowired
	private ForumSectionDao forumSectionDao;

	@Override
	public List<ForumSectionVo> listSection(Integer forumId) {
		List<ForumSectionVo> voList = Lists.newArrayList();
		try {
			List<ForumSection> sectionList = forumSectionDao.listByForum(forumId);
			for (ForumSection forumSection : sectionList) {
				ForumSectionVo vo = new ForumSectionVo();
				vo.setId(forumSection.getId());
				vo.setName(forumSection.getName());
				voList.add(vo);
			}
		} catch (Exception e) {
			logger.error("", e);
		}
		return voList;
	}

	// 批量插入版块
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Integer batchInsert(List<ForumSection> forumSectionList, Date now) {
		Integer count = 0;
		for (ForumSection forumSection : forumSectionList) {
			if (StringUtils.isNotBlank(forumSection.getUrl())) {
				forumSection.setCreateTime(now);
				forumSection.setUpdateTime(now);
				Integer c = forumSectionDao.updateByUrl(forumSection);
				if (c == 0) {
					forumSection.setUpdateTime(null);
					forumSectionDao.insert(forumSection);
					count++;
				} else {
					count += c;
				}
			}
		}
		return count;
	}

}
